//
//  GenericLoanViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/11/15.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

class GenericLoanViewController: KMViewController {
    
    fileprivate let cellId = "genericLoanCell"
    fileprivate var dataArray = [GenericLoansModel]()
    
    fileprivate var workType = "" //职业身份
    fileprivate var loanSum = "" //贷款额度
    fileprivate var mortgage = "" //抵押类型
    fileprivate var moreTypeDic = [String:String]() //更多贷款信息
    
    fileprivate let headView = GenericLoanHeadView() //头部视图
    fileprivate var selectLoanView : SelectLoanTypeView! //贷款类型选择
    fileprivate var searchView : LoanSearchView! //搜索框
    fileprivate var moreTypeView : MoreLoanTypeView! //更多贷款类型
    
    fileprivate var tableView : UITableView!
    fileprivate let cityLabel = UILabel()
    
    fileprivate var curLoction = "" //当前城市
    fileprivate var page = 1
    
    init(workType:String?=nil,loanSum:String?=nil,mortgage:String?=nil) {
        super.init(nibName: nil, bundle: nil)
        
        self.workType = workType ?? workStatus
        self.loanSum = loanSum ?? loanLimit
        self.mortgage = mortgage ?? mortgageType
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = generalLoan
        createRightButton()
        createTableView()
    }
    
    //MARK: 导航栏右键
    fileprivate func createRightButton() {
        
        let button = UIButton()
        button.addTarget(self, action: #selector(selectCity(sender:)), for: .touchUpInside)
        self.navigationController?.navigationBar.addSubview(button)
        
        
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "location")
        button.addSubview(imageView)
        
        
        cityLabel.text = self.curLoction
        cityLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        cityLabel.textColor = UIColor.white
        button.addSubview(cityLabel)
        
        if let city = KMTool.stringForEnumKey(.currentCity) {
            self.cityLabel.text = city
            self.curLoction = city
        }
        
        button.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(RATIO(maxNum: -8))
            make.centerY.height.equalToSuperview()
            make.width.equalTo(RATIO(maxNum: 120))
        }
        
        cityLabel.snp.makeConstraints { (make) in
            make.right.centerY.equalToSuperview()
            make.width.greaterThanOrEqualTo(10)
            make.height.greaterThanOrEqualTo(10)
        }
        
        imageView.snp.makeConstraints { (make) in
            make.right.equalTo(cityLabel.snp.left)
            make.centerY.equalTo(cityLabel)
            make.width.height.equalTo(RATIO_H(maxNum: 20))
        }
        
        
        
    }
    
    
    //MARK: 选择城市
    @objc fileprivate func selectCity(sender:UIButton) {
        
        let cityVC = CityViewController.init(currentCity:self.curLoction)
        cityVC.cityBlock = {[weak self] (cityName) in
            self?.cityLabel.text = cityName
            
            self?.moreTypeView.isHidden = true
            self?.headView.moreButton.image = UIImage.init(named: "double_arrow_right")
            self?.hideTypeView()
            
            self?.page = 1
            self?.getData()
        }
        self.navigationController?.pushViewController(cityVC, animated: true)
    }
    
    //MARK: 创建tableView
    fileprivate func createTableView() {
        
        headView.workButton.text = self.workType
        headView.linesButton.text = self.loanSum
        headView.typeButton.text = self.mortgage
        headView.delegate = self
        headView.moreButton.addTarget(self, action: #selector(moreAction(sender:)), for: .touchUpInside)
        self.view.addSubview(headView)
        
        searchView = LoanSearchView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 50)))
        searchView.number = "0"
        searchView.searchBtn.addTarget(self, action: #selector(searchData), for: .touchUpInside)
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(NewCityLoanCell.self, forCellReuseIdentifier: cellId)
        tableView.separatorStyle = .none
        tableView.tableHeaderView = searchView
        self.view.addSubview(tableView)
        
        selectLoanView = SelectLoanTypeView.init(workType: self.workType, loanSum: self.loanSum, mortgage: self.mortgage)
        selectLoanView.delegate = self
        selectLoanView.isHidden = true
        self.view.addSubview(selectLoanView)
        
        moreTypeView = MoreLoanTypeView()
        moreTypeView.isHidden = true
        moreTypeView.delegate = self
        self.view.addSubview(moreTypeView)
        
        headView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        selectLoanView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        moreTypeView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        KMTool.setRefresh(with: tableView, headerAction: {[weak self] in
            
            self?.page = 1
            self?.getData()
            
        }) {[weak self] in
            
            self?.getData()
        }
        
        self.tableView.mj_header.beginRefreshing()
        
    }
    
    //MARK: 搜索数据
    @objc fileprivate func searchData() {
        
        //隐藏键盘
        self.view.endEditing(true)
        
        self.page = 1
        self.getData()
    }
    
    //MARK: 加载数据
    fileprivate func getData() {
        
        var parameters = ["psw":"kameng98_loan"]
        
        //职业身份
        if selectLoanView.workType == unlimited {
            parameters.removeValue(forKey: "identity")
        }else{
            if selectLoanView.workType == civilServiceSoes {
                parameters["identity"] = civilServiceOrSoes
            }else{
                parameters["identity"] = selectLoanView.workType
            }
        }
        
        //贷款额度
        if selectLoanView.loanSum == unlimited {
            parameters.removeValue(forKey: "money")
        }else{
            parameters["money"] = selectLoanLimit(title: selectLoanView.loanSum)
        }
        
        //抵押类型
        if selectLoanView.mortgage == unlimited {
            parameters.removeValue(forKey: "mortgage_type")
        }else{
            parameters["mortgage_type"] = selectMortgageType(title: selectLoanView.mortgage)
        }
        
        //放款时间
        if let lend = self.moreTypeDic["lend"] {
            if lend == unlimited {
                parameters.removeValue(forKey: "time_advange")
            }else{
                parameters["time_advange"] = selectLendersTime(title: lend)
            }
        }
        
        //借款期限
        if let borrow = self.moreTypeDic["borrow"] {
            if borrow == unlimited {
                parameters.removeValue(forKey: "loan_maxtime")
            }else{
                parameters["loan_maxtime"] = selectBorrowTime(title: borrow)
            }
        }
        
        //机构类型
        if let institutions = self.moreTypeDic["institutions"] {
            if institutions == unlimited {
                parameters.removeValue(forKey: "organization_type")
                parameters.removeValue(forKey: "organization_list")
            }else{
                
                if moreTypeView.selectIndex == 4 {//银行
                    if institutions == bank_title || institutions == unlimitedBank{
                        parameters.removeValue(forKey: "organization_list")
                    }else{
                        parameters["organization_list"] = institutions
                    }
                    
                    
                }else{
                    parameters["organization_type"] = institutions
                }
            }
        }
        
        //还款方式
        if let repayment = self.moreTypeDic["repayment"]{
            
            if repayment == unlimited {
                parameters.removeValue(forKey: "repayment")
            }else{
                parameters["repayment"] = repayment
            }
        }
        
        //用途
        if let use = self.moreTypeDic["use"] {
            if use == unlimited {
                parameters.removeValue(forKey: "loan_use")
            }else{
                parameters["loan_use"] = use
            }
        }
        
        parameters["p"] = "\(self.page)"
        parameters["city"] = curLoction //城市
        parameters["keyword"] = self.searchView.searchView.text //搜索关键词
        
        KMTool.requestMethod(.get, URLString: url_genericLoans, parameters: parameters, success: { (value, json) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            self.searchView.number = json["count"].stringValue
            
            if self.page == 1 {
                self.dataArray.removeAll()
            }
            
            if let array = json["data"].arrayObject as? [[String:Any]] {
                
                if array.count > 0 {
                    self.page += 1
                }
                
                for item in array {
                    let model = GenericLoansModel.setModel(with: item)
                    self.dataArray.append(model)
                    
                }
                
                
            }
            
            self.tableView.reloadData()
            
            
        }) {
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
        }
    }
    
    //MARK: 隐藏选择类型视图
    fileprivate func hideTypeView() {
        
        self.selectLoanView.isHidden = true
        self.headView.workButton.image = UIImage.init(named: "bottom_arrow")
        self.headView.linesButton.image = UIImage.init(named: "bottom_arrow")
        self.headView.typeButton.image = UIImage.init(named: "bottom_arrow")
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        hideTypeView()
    }
    
    //MARK: 选择贷款额度
    fileprivate func selectLoanLimit(title:String) -> String {
        
        let array = [unlimited,lessTwo,twoToFive,fiveToTen,tenToFifty,fiftyToHundred,greateHundred]
        let numbers = ["","0-2","2-5","5-10","10-50","50-100","100-99999999"]
        let index = array.index(of: title)
        
        return numbers[index ?? 0]
    }
    
    //MARK: 选择抵押类型
    fileprivate func selectMortgageType(title:String) -> String {
        
        let array = [unlimited,noCollateral,carCollateral,houseCollateral,pledge,guarantee,otherCollateral]
        let typeArray = ["","2","4","3","5","6","1"]
        let index = array.index(of: title)
        
        return typeArray[index ?? 0]
    }
    
    //MARK: 选择放款时间
    fileprivate func selectLendersTime(title:String) -> String {
        
        let array = [unlimited,lendersOfTheday,oneToThreeDay,greateThreeDay]
        let timeArray = ["","当天放款","一至三天放款","三天以上放款"]
        let index = array.index(of: title)
        
        return timeArray[index ?? 0]
    }
    
    //MARK: 选择借款期限
    fileprivate func selectBorrowTime(title:String) -> String {
        
        let array = [unlimited,lessSixMonth,sixToOneYear,oneToTwoYear,twoToThreeYear,threeToFiveYear,greateFiveYear]
        let timeArray = ["","六个月内","六个月至一年","一年至二年","二年至三年","三年至五年","五年以上"]
        let index = array.index(of: title)
        
        return timeArray[index!]
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

extension GenericLoanViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 160)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? NewCityLoanCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = dataArray[indexPath.row]
        
        let loanDetailsWebVC = LoanDetailsWebViewController.init(urlStr: model.id!,title:model.organization_name! + "-" + model.product_name!)
        loanDetailsWebVC.removeElements = ["top-bar","footer"]
        self.navigationController?.pushViewController(loanDetailsWebVC, animated: true)
    }
    
}

extension GenericLoanViewController : GenericLoanHeadViewdelegate,SelectLoanTypeViewDelegate {
    
    //MARK: 选择贷款类型
    func selectLoanType(index: Int) {
        
        //隐藏键盘
        self.view.endEditing(true)
        
        selectLoanView.loanType = index
        moreTypeView.isHidden = true
        headView.moreButton.image = UIImage.init(named: "double_arrow_right")
        
        switch index {
        case 1:
            headView.linesButton.image = UIImage.init(named: "bottom_arrow")
            headView.typeButton.image = UIImage.init(named: "bottom_arrow")
            if headView.workButton.image == UIImage.init(named: "up_arrow") {
                self.selectLoanView.isHidden = true
                headView.workButton.image = UIImage.init(named: "bottom_arrow")
            }else{
                self.selectLoanView.isHidden = false
                headView.workButton.image = UIImage.init(named: "up_arrow")
            }
            selectLoanView.dataArray = [unlimited,students,freelance,working,individual,businessOwners,civilServiceSoes]
            
        case 2:
            headView.workButton.image = UIImage.init(named: "bottom_arrow")
            headView.typeButton.image = UIImage.init(named: "bottom_arrow")
            if headView.linesButton.image == UIImage.init(named: "up_arrow") {
                headView.linesButton.image = UIImage.init(named: "bottom_arrow")
                self.selectLoanView.isHidden = true
            }else{
                headView.linesButton.image = UIImage.init(named: "up_arrow")
                self.selectLoanView.isHidden = false
            }
            selectLoanView.dataArray = [unlimited,lessTwo,twoToFive,fiveToTen,tenToFifty,fiftyToHundred,greateHundred]
        case 3:
            headView.workButton.image = UIImage.init(named: "bottom_arrow")
            headView.linesButton.image = UIImage.init(named: "bottom_arrow")
            if headView.typeButton.image == UIImage.init(named: "up_arrow") {
                headView.typeButton.image = UIImage.init(named: "bottom_arrow")
                self.selectLoanView.isHidden = true
            }else{
                headView.typeButton.image = UIImage.init(named: "up_arrow")
                self.selectLoanView.isHidden = false
            }
            selectLoanView.dataArray = [unlimited,noCollateral,carCollateral,houseCollateral,pledge,guarantee,otherCollateral]
        default:
            break
        }
    }
    
    //MARK: 更多
    @objc fileprivate func moreAction(sender:ButtonView) {
        
        //隐藏键盘
        self.view.endEditing(true)
        
        moreTypeView.isHidden = !moreTypeView.isHidden
        
        if !moreTypeView.isHidden {
            sender.image = UIImage.init(named: "up_arrow")
        }else{
            sender.image = UIImage.init(named: "double_arrow_right")
        }
        
        hideTypeView()
    }
    
    //MARK: 选择贷款标题
    func selectLoanTitle(title: String) {
        
        hideTypeView()
        
        switch selectLoanView.loanType {
        case 1:
            
            if title == headView.workButton.text {
                return
            }

            self.headView.workButton.text = title
            if title == unlimited{
                self.headView.workButton.text = workStatus
                selectLoanView.workType = unlimited
            }else if title == civilServiceSoes {
                self.headView.workButton.text = civilService
                selectLoanView.workType = civilServiceSoes
            }
            
            selectLoanView.workType = title
            
        case 2:
            
            if title == headView.linesButton.text {
                return
            }
            
            self.headView.linesButton.text = title
            if title == unlimited{
                self.headView.linesButton.text = loanLimit
                selectLoanView.loanSum = unlimited
            }
            
            selectLoanView.loanSum = title
            
        case 3:
            
            if title == headView.typeButton.text {
                return
            }
            
            self.headView.typeButton.text = title
            if title == unlimited{
                self.headView.typeButton.text = mortgageType
                selectLoanView.mortgage = unlimited
            }
            
            selectLoanView.mortgage = title
            
        default:
            break
        }
        
        self.page = 1
        self.getData()
    }
}

extension GenericLoanViewController : MoreLoanTypeViewDelegate {
    
    //MARK: 确认选择
    func selectLoanType() {
        
        moreTypeView.isHidden = true
        headView.moreButton.image = UIImage.init(named: "double_arrow_right")
        self.page = 1
        self.getData()
    }
    
    //MARK: 取消选择
    func cancelSelect() {
        
        moreTypeView.isHidden = true
        headView.moreButton.image = UIImage.init(named: "double_arrow_right")
    }
    
    //MARK: 选择贷款详情
    func selectLoanDetails(title: String,text:String) {
    
        switch title {
        case lendingTime://放款时间
            self.moreTypeDic["lend"] = text
        case durationofBorrowing://借款期限
            self.moreTypeDic["borrow"] = text
        case typeofInstitution://机构类型
            self.moreTypeDic["institutions"] = text
        case repaymentMethod://还款方式
            self.moreTypeDic["repayment"] = text
        case use://用途
            self.moreTypeDic["use"] = text
        default:
            break
        }
    }
    
    //MAKR: 选择贷款银行
    func selectLoanBankType(title: String) {
        
        self.moreTypeDic["institutions"] = title
    }
}

